package com.hawk.eye.framework.plugins.webhook;


import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;

public class ExternalJarLoader {

    public <T> List<T> loadJar(String path, Class<T> target) {
        File[] jars = new File(path).listFiles((dir, name) -> name.toLowerCase().endsWith(".jar"));
        List<T> instances = new ArrayList<>();
        try {
            if (jars != null) {
                for (File jar : jars) {
                    URL[] urls = new URL[0];

                    urls = new URL[]{jar.toURI().toURL()};
                    try (URLClassLoader classLoader = new URLClassLoader(urls, this.getClass().getClassLoader())) {
                        ServiceLoader<T> serviceLoader = ServiceLoader.load(target, classLoader);
                        serviceLoader.forEach(instances::add);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("加载插件库失败", e);
        }
        return instances;
    }

}